<?php

namespace app\admin\service;

use app\admin\validate\SetCityValidate;
use support\spark\exception\ApiException;
use support\spark\model\system\SetCity;

class CityService
{


    /**
     * 获取城市列表
     * @param $where
     * @param $level
     * @return array|\think\response\Json
     */
    public function getList($where, $level)
    {
        $cityModel = new SetCity();
        if (request()->isAjax()) {
            $list = $cityModel->getAllList($where, ["id", "pid", "name", "level", "is_show"], ["id" => "asc"]);
            // $list=$list->toArray();
            foreach ($list as $key => $vo) {
                if ($level <= 1) {
                    $list[$key]['hasChildren'] = true;
                    $list[$key]['children'] = [];
                }
            }
            return dataReturn(0, 'success', $list);
        }

        $list = $cityModel->getAllList($where, ["id", "pid", "name", "level", "is_show"], ["id" => "asc"]);
        //$list=$list->toArray();
        foreach ($list as $key => $vo) {
            $list[$key]['hasChildren'] = true;
            $list[$key]['children'] = [];
        }


        return dataReturn(0, 'success', $list);
    }

    /**
     * 添加城市
     * @param $param
     * @return array|\think\response\Json
     */
    public function addCity($param)
    {
        // 检验完整性
        $validate = new SetCityValidate();
        if (!$validate->check($param)) {
            throw new  ApiException($validate->getError(), -1);
        }

        $setCityModel = new SetCity();
        $has = $setCityModel->checkUnique([
            'name' => $param['name'],
            'pid' => $param['pid'],
        ]);
        if (!empty($has)) {
            throw new  ApiException('名称已经存在', -1);
        }
        $setCityModel->insertOne($param);
        return dataReturn(0, '添加成功');
    }

    /**
     * 编辑城市
     * @param $param
     * @return array|\think\response\Json
     */
    public function editCity($param)
    {
        // 检验完整性
        $validate = new SetCityValidate();
        if (!$validate->check($param)) {
            throw new  ApiException($validate->getError(), -1);
        }
        $setCityModel = new SetCity();

        $where[] = ['id', '<>', $param['id']];
        $where[] = ['name', '=', $param['name']];
        $has = $setCityModel->checkUnique($where);

        if (!empty($has)) {
            throw new  ApiException('名称已经存在', -1);
        }
        $setCityModel->updateById($param, $param['id']);
        return dataReturn(0, '编辑成功');
    }

    /**
     * 地区tree
     * @return array
     */
    public function getAreaTree()
    {
        $cityModel = new SetCity();
        $where[] = ['level', '<=', 3];
        $list = $cityModel->getAllList($where, ["id", "pid", "name", "level", "is_show"], ["id" => "asc"]);
        $tree = makeTree($list);

        return dataReturn(0, 'success', $tree);
    }
}